#include "AnimatedSplashScreen.h"
#include <QPainter>
#include <QVBoxLayout>
#include <QLabel>
#include <QTimer>
#include <QFont>
#include <QApplication>

AnimatedSplashScreen::AnimatedSplashScreen(const QString &userName, QWidget *parent)
    : QWidget(parent), m_opacity(1.0), m_userName(userName)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::SplashScreen);
    setFixedSize(500, 400);

    setupUI();

    // 创建淡出动画
    m_fadeAnimation = new QPropertyAnimation(this, "opacity");
    m_fadeAnimation->setDuration(1000);  // 1秒动画
    m_fadeAnimation->setStartValue(1.0);
    m_fadeAnimation->setEndValue(0.0);

    connect(m_fadeAnimation, &QPropertyAnimation::finished, this, &AnimatedSplashScreen::finished);
}

void AnimatedSplashScreen::setupUI()
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setSpacing(10);
    layout->setContentsMargins(20, 40, 20, 40);

    // 应用标题
    QLabel *titleLabel = new QLabel("❤️投E行", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("QLabel { color: white; font-size: 32px; font-weight: bold; margin-bottom: 20px; }");

    // 欢迎信息
    m_welcomeLabel = new QLabel("欢迎使用", this);
    m_welcomeLabel->setAlignment(Qt::AlignCenter);
    m_welcomeLabel->setStyleSheet("QLabel { color: white; font-size: 24px; margin-bottom: 10px; }");

    // 用户信息
    m_userLabel = new QLabel("", this);
    m_userLabel->setAlignment(Qt::AlignCenter);
    m_userLabel->setStyleSheet("QLabel { color: #e74c3c; font-size: 20px; font-weight: bold; }");

    // 设置用户欢迎信息
    setUserName(m_userName);

    layout->addStretch();
    layout->addWidget(titleLabel);
    layout->addWidget(m_welcomeLabel);
    layout->addWidget(m_userLabel);
    layout->addStretch();

    // 设置渐变背景
    setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:1, "
                  "stop:0 #2c3e50, stop:0.5 #3498db, stop:1 #2c3e50);");
}

void AnimatedSplashScreen::setOpacity(float opacity)
{
    m_opacity = opacity;
    update();  // 触发重绘
}

void AnimatedSplashScreen::setUserName(const QString &userName)
{
    m_userName = userName;
    if (!m_userName.isEmpty()) {
        m_userLabel->setText(QString("欢迎，%1").arg(m_userName));
    } else {
        m_userLabel->setText("");
    }
}

void AnimatedSplashScreen::startAnimation()
{
    // 显示3秒后开始淡出动画
    QTimer::singleShot(3000, this, [this]() {
        m_fadeAnimation->start();
    });
}

void AnimatedSplashScreen::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setOpacity(m_opacity);
    painter.fillRect(rect(), QColor(44, 62, 80));

    // 添加一些装饰性元素
    painter.setPen(QPen(QColor(255, 255, 255, 100), 2));
    painter.drawRect(10, 10, width()-20, height()-20);

    // 调用基类的paintEvent以确保子控件正确绘制
    QWidget::paintEvent(event);
}
